<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="800px"
    @close="close"
  >
    <el-card shadow="hover">
      <vab-query-form>
        <vab-query-form-left-panel :span="12">
          <el-button
            icon="el-icon-plus"
            type="primary"
            @click="
              () => (
                (houseTypeTitle = '新建户型'),
                (isEdit = false),
                (dialogHouseTypeVisible = true)
              )
            "
          >
            新建户型
          </el-button>
          <!-- <el-button icon="el-icon-delete" type="danger" @click="handleDelete">
          删除
        </el-button> -->
        </vab-query-form-left-panel>
      </vab-query-form>
      <el-table
        ref="tableSort"
        v-loading="listLoading"
        :data="list"
        :element-loading-text="elementLoadingText"
        :height="height"
      >
        <el-table-column
          show-overflow-tooltip
          prop="projectName"
          label="项目名称"
          width="100px"
        ></el-table-column>
        <el-table-column
          show-overflow-tooltip
          label="户型类型"
          prop="houseTypeNme"
          width="100px"
        ></el-table-column>
        <el-table-column
          show-overflow-tooltip
          label="户型面积（平方米）"
          prop="constructionArea"
          width="150px"
        ></el-table-column>
        <el-table-column
          show-overflow-tooltip
          label="每平米价格(万元)"
          prop="price"
          width="150px"
        ></el-table-column>
        <el-table-column show-overflow-tooltip label="操作" width="200px">
          <template #default="{ row }">
            <el-button type="primary" @click="editHouseType(row)">
              编辑
            </el-button>
            <el-button type="danger" @click="removeHouseType(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      append-to-body
      :title="houseTypeTitle"
      :visible.sync="dialogHouseTypeVisible"
      width="700px"
      @closed="closeHouseType"
    >
      <el-form
        ref="houseTypeForm"
        :model="houseTypeForm"
        :rules="houseRules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="户型名称" prop="houseTypeId">
              <el-select
                v-model="houseTypeForm.houseTypeId"
                collapse-tags
                placeholder="请选择"
                size="medium"
              >
                <el-option
                  v-for="item in houseTypeIds"
                  :key="item.typeId"
                  :label="item.typeName"
                  :value="item.typeId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="建筑面积(平方米)" prop="constructionArea">
              <el-input-number
                v-model.trim="houseTypeForm.constructionArea"
                autocomplete="off"
                :min="0"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="标签" prop="estatesTags">
              <el-select
                v-model="houseTypeForm.estatesTags"
                multiple
                collapse-tags
                placeholder="请选择"
                size="medium"
              >
                <el-option
                  v-for="item in houseTags"
                  :key="item.constantId"
                  :label="item.constantValue"
                  :value="item.constantId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每平米价格(万元)" prop="price">
              <el-input-number
                v-model.trim="houseTypeForm.price"
                autocomplete="off"
                :min="0"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="图片（一张）" prop="imgId">
          <el-upload
            ref="imageUrl"
            :file-list="imageUrlfileList"
            action="imageUrl"
            :before-upload="imageUrlBeforeUpload"
            name="file"
            :http-request="uploadImage"
            list-type="picture-card"
            :limit="1"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeHouseType">取 消</el-button>
        <el-button type="primary" @click="addHousesType">添 加</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
  import { setExtraInfo } from '@/api/building'
  import { getByType, getHouseType } from '@/api/tag'
  import {
    addHouseType,
    getAllHouseType,
    deleteHouseType,
    updateHouseType,
  } from '@/api/house'
  import _net from '../../../config/net.config'
  import { upload } from '@/api/upload'
  import _, { cloneDeep } from 'lodash'
  export default {
    name: 'AddHouseType',
    data() {
      return {
        isEdit: false,
        houseTypeTitle: '新建户型',
        buildingTags: [],
        houseTags: [],
        houseTypeIds: [],
        buildingTagsValue: [],
        imageUrlfileList: [],
        extraForm: {
          estateId: '',
          imgs: [],
          priceMax: 0,
          priceMin: 0,
          tags: [],
        },
        buildingVo: [],
        Houses: [],
        houseRules: {
          estatesTags: [
            { required: true, trigger: 'blur', message: '请选择户型标签' },
          ],
          houseTypeId: [
            { required: true, trigger: 'blur', message: '请选择户型名称' },
          ],
          priceMax: [
            { required: true, trigger: 'blur', message: '请输入最高价格' },
          ],
          imgId: [
            { required: true, trigger: 'blur', message: '请上传户型图片' },
          ],
        },

        houseTypeForm: {
          businessRealEstateId: '',
          constructionArea: 0,
          estatesTags: '',
          estatesTagIds: '',
          houseTypeId: '',
          imgId: '',
          price: 0,
        },
        title: '',
        dialogFormVisible: false,
        dialogHouseTypeVisible: false,
        show: false,
        list: [],
        listLoading: false,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        background: true,
        elementLoadingText: '正在加载...',
      }
    },
    computed: {
      height() {
        return this.$baseTableHeight()
      },
    },
    methods: {
      //添加户型
      addHousesType() {
        let item = _.cloneDeep(this.houseTypeForm)
        item.price = Number(this.houseTypeForm.price)
        item.constructionArea = Number(this.houseTypeForm.constructionArea)
        item.businessRealEstateId = this.buildingVo.floorId
        //处理estatesTags
        item.estatesTags = this.houseTypeForm.estatesTags.toString()
        if (item.constructionArea == 0) {
          this.$baseMessage('建筑面积不能为0', 'error')
          return
        } else if (item.price == 0) {
          this.$baseMessage('价格不能为0', 'error')
          return
        }
        this.$refs['houseTypeForm'].validate(async (valid) => {
          if (valid) {
            if (!this.isEdit) {
              item.estatesTagIds = item.estatesTags
            }
            const { data } = this.isEdit
              ? await updateHouseType(item)
              : await addHouseType(item)
            if (data.status == 0) {
              this.$baseMessage('操作成功！', 'success')
              this.getBindHouseType()
              this.dialogHouseTypeVisible = false
              this.closeHouseType()
            } else {
              this.$message.error(data.message)
            }
          } else {
            return false
          }
        })
      },
      imageUrlBeforeUpload(file) {
        let isRightSize = file.size / 1024 / 1024 < 2
        if (!isRightSize) {
          this.$message.error('文件大小超过 2MB')
        }
        return isRightSize
      },
      async uploadImage(param) {
        const formData = new FormData()
        formData.append('fileType', 1)
        formData.append('file', param.file)
        console.log(formData)
        const { data } = await upload(formData)
        this.dialogHouseTypeVisible
          ? (this.houseTypeForm.imgId = data.body.fileId)
          : this.extraForm.imgs.push(data.body.fileId)
      },
      //获取绑定后过的户型
      async getBindHouseType() {
        const { data } = await getAllHouseType({
          businessEstateId: this.extraForm.estateId,
        })
        if (data.status === 0) {
          if (data.body.length != 0) {
            this.list = data.body
          }
        }
      },
      showEdit(row) {
        if (row) {
          this.title = '户型配置'
          this.show = true
          this.Houses = []
          this.buildingVo = _.cloneDeep(row)
          this.extraForm.estateId = row.floorId
          this.fetchBuildingTagData()
          this.fetchHouseTagData()
          this.fetchHouseIdData()
          this.getBindHouseType()
        }
        this.dialogFormVisible = true
      },
      close() {
        console.log('准备关闭')
        // this.$refs['extraForm'].resetFields()
        this.dialogFormVisible = false
        this.list = []
        this.extraForm = {
          estateId: '',
          imgs: [],
          priceMax: 0,
          priceMin: 0,
          tags: [],
        }
      },
      closeHouseType() {
        this.dialogHouseTypeVisible = false
        this.imageUrlfileList = []
        // this.$refs['houseTypeForm'].resetFields()
        this.houseTypeForm = {
          businessRealEstateId: '',
          constructionArea: 0,
          estatesTags: '',
          estatesTagIds: '',
          houseTypeId: '',
          imgId: '',
          price: 0,
        }
      },
      // 保存额外信息
      // save() {
      //   if (this.extraForm.tags.length == 0) {
      //     this.$baseMessage('请上传样图', 'error')
      //     return 0
      //   } else if (this.extraForm.priceMax == 0) {
      //     this.$baseMessage('最高价不能为0', 'error')
      //   } else if (this.extraForm.priceMin == 0) {
      //     this.$baseMessage('最低价不能为0', 'error')
      //   }
      //   this.$refs['extraForm'].validate(async (valid) => {
      //     if (valid) {
      //       let item = _.cloneDeep(this.extraForm)
      //       item.tags = this.extraForm.tags.toString()
      //       item.imgs = this.extraForm.imgs.toString()
      //       item.priceMax = Number(item.priceMax)
      //       item.priceMin = Number(item.priceMin)
      //       const { data } = await setExtraInfo(item)
      //       this.$baseMessage(data.message, 'success')
      //       this.$emit('fetch-data')
      //       this.close()
      //     }
      //   })
      // },
      async fetchBuildingTagData() {
        let pushData = {}
        pushData.type = 4
        const { data } = await getByType(pushData)
        this.buildingTags = data.body
        this.$baseNotify('地产标签获取完毕！', '成功', 'success', 'top-right')
      },
      async fetchHouseTagData() {
        let pushData = {}
        pushData.type = 2
        const { data } = await getByType(pushData)
        this.houseTags = data.body
        this.$baseNotify('房源标签获取完毕！', '成功', 'success', 'top-right')
      },
      async fetchHouseIdData() {
        const { data } = await getHouseType()
        this.houseTypeIds = data.body
        this.$baseNotify('房源ID获取完毕！', '成功', 'success', 'top-right')
      },
      async editHouseType(item) {
        this.isEdit = true
        this.houseTypeTitle = '编辑户型'
        console.log(item)
        let temp = item
        let base = _net.baseURL
        const element = base + '/file/download?fileId=' + item.imgId
        this.imageUrlfileList.push({
          url: element,
          id: item.imgId,
        })
        temp.estatesTags = item.estatesTagIds.split(',')
        this.houseTypeForm = _.cloneDeep(item)
        this.dialogHouseTypeVisible = true
      },
      async removeHouseType(item) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          let _pushForm = _.cloneDeep(item)
          // _pushForm.businessRealEstateId = item.businessRealEstateId
          // _pushForm.houseTypeId = item.houseTypeId
          // _pushForm.id = item.id
          const { data } = await deleteHouseType(_pushForm)
          if (data.status == 0) {
            this.$baseMessage('删除成功！', 'success')
            this.getBindHouseType()
          } else {
            this.$message.error(data.message)
          }
        })
      },
      addHouse() {
        this.dialogHouseTypeVisible = true
      },
    },
  }
</script>
<style lang="scss" scoped>
  .vab-upload {
    z-index: 9999 !important;
  }
</style>
